package com.qst.service.impl;

import com.qst.ExamException;
import com.qst.dao.*;
import com.qst.entity.Schedule;
import com.qst.entity.User;
import com.qst.service.ScheduleService;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;

@Service
public class ScheduleServiceImpl implements ScheduleService {
    private ScheduleDao scheduleDAO = DAOFactory.getDao(ScheduleDao.class);
    private AssessmentTypeDao assessmentDAO = DAOFactory.getDao(AssessmentTypeDao.class);
    private TeamDao teamDAO = DAOFactory.getDao(TeamDao.class);
    private UserDao userDao = DAOFactory.getDao(UserDao.class);

    @Override
    public List<Schedule> findByCreator(User user) {
        try {
            List<Schedule> scheduleList = scheduleDAO.findByCreatorId(user.getId());
            for (Schedule h : scheduleList) {
                h.setCreator(user);
                h.setAssessmentType(assessmentDAO.findById(h.getAssessmentId()));
                h.setTeam(teamDAO.findById(h.getTeamId()));
            }
            return scheduleList;
        } catch (SQLException ex) {
            throw new ExamException("查询测试安排出错", ex);
        }
    }

    @Override
    public Schedule findById(Integer id) {
        try {
            Schedule h = scheduleDAO.findById(id);
            h.setCreator(userDao.findById(h.getCreatorId()));
            h.setAssessmentType(assessmentDAO.findById(h.getAssessmentId()));
            h.setTeam(teamDAO.findById(h.getTeamId()));
            return h;
        } catch (SQLException e) {
            throw new ExamException("查询测试安排出错", e);
        }
    }

    @Override
    public void saveSchedule(Schedule h) {
        try {
            scheduleDAO.save(h);
        } catch (SQLException e) {
            throw new ExamException("添加测试安排出错", e);
        }
    }

    @Override
    public Schedule deleteSchedule(Integer id) {
        try {
            Schedule sche = scheduleDAO.findById(id);
            if (sche.getStatus() > 1) {
                throw new ExamException("只有未开始或作废的安排才能删除");
            }
            scheduleDAO.delete(sche.getId());
            return sche;
        } catch (SQLException e) {
            throw new ExamException("删除测试安排出错", e);
        }
    }

    @Override
    public void updateSchedule(Schedule h) {
        try {
            scheduleDAO.update(h);
        } catch (SQLException e) {
            throw new ExamException("更新测试安排出错", e);
        }
    }
}
